package com.googlecode.cswish.struts.hibernate;

import org.hibernate.dialect.SQLServerDialect;

/**
 * @see http://love2java.javaeye.com/blog/422389
 * 
 * @author jerry.feng
 *
 */
public class SQLServerDialectEx extends SQLServerDialect {

	@Override
	public String getLimitString(String querySelect, int offset, int limit) {
		if (offset == 0) {
			return super.getLimitString(querySelect, 0, limit);
		} else {
			String select;
			String orderBy;
			String query = querySelect.toLowerCase();
			
			int orderByIndex = query.lastIndexOf("order by ");
			if (orderByIndex > 0) {
				select = query.substring(0, orderByIndex);
				orderBy = query.substring(orderByIndex, query.length());
			} else {
				select = query;
				int firstColumnBegin = query.indexOf(' ');
				int firstColumnEnd = query.indexOf(' ', firstColumnBegin + 1);
				String firstColumn = query.substring(firstColumnBegin + 1, firstColumnEnd);
				orderBy = "order by " + firstColumn;
			}
			
			int fromIndex = select.indexOf("from");
			String selectFld = select.substring(0, fromIndex);
			String selectFromTableAndWhere = select.substring(fromIndex);
			StringBuilder sql = new StringBuilder(query.length() + 100);
			sql.append("select * from (").append(selectFld).append(
					",ROW_NUMBER() OVER(").append(orderBy).append(
					") as _page_row_num_hb ").append(selectFromTableAndWhere)
					.append(" ) temp ").append(
							" where  _page_row_num_hb BETWEEN  ").append(
							offset + 1).append(" and ").append(limit);
			return sql.toString();
		}
	}

	@Override
	public boolean supportsLimitOffset() {
		return true;
	}
}